/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.binding;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
import org.apache.ibatis.io.ResolverUtil;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;

/**
 * @author Clinton Begin
 * @author Eduardo Macarron
 * @author Lasse Voss
 */
/*xxx: Mapper接口 及其 对应的 代理对象工厂 的注册中心*/
  /*xxx： Mapper注册表*/
public class MapperRegistry {

  /*xxx: mybatis全局性的配置对象，在MyBatis初始化的过程中，所有配置信息会被 解析成相应的对象
  *   并 记录到 Configuration对象中*/
  private final Configuration config;

  /*xxx: 记录了  Mapper接口 与 对应 MapperProxyFactory之间的关系*/
  private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

  public MapperRegistry(Configuration config) {
    this.config = config;
  }

  @SuppressWarnings("unchecked")
  /*xxx: 需要执行某SQL时， 会调用该方法，获取实现了相应接口的代理对象*/
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    /*xxx: 查找指定 type 对应的 MapperProxyFactory对象*/
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      /*xxx: 如果未找到，则抛出异常*/
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      /*xxx: 创建 实现了  type 接口的代理对象*/
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }
  /*xxx: 意味着，同一个类型，只能被一个 mapper进行映射*/
  public <T> boolean hasMapper(Class<T> type) {
    return knownMappers.containsKey(type);
  }

  /*xxx: 初始过程中，会调用 该方法，填充 knownMappers集合，该集合的 key 为 Mapper接口对应的Class对象
   *   value 为  MapperProxyFactory工厂对象,它可以为 Mapper接口创建代理对象*/
  public <T> void addMapper(Class<T> type) {
    /*xxx: 检测type是否为 接口,不是接口，则直接跳过*/
    if (type.isInterface()) {
      /*xxx: 检测 是否已经加载过该接口*/
      if (hasMapper(type)) {
        throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
      }
      boolean loadCompleted = false;
      try {
        /*xxx: 添加到  knownMappers集合*/
        knownMappers.put(type, new MapperProxyFactory<>(type));
        // It's important that the type is added before the parser is run
        // otherwise the binding may automatically be attempted by the
        // mapper parser. If the type is already known, it won't try.
        /*xxx: 对 XML 解析 和注解的处理*/
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        parser.parse();
        loadCompleted = true;
      } finally {
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
  }

  /**
   * Gets the mappers.
   *
   * @return the mappers
   * @since 3.2.2
   */
  public Collection<Class<?>> getMappers() {
    return Collections.unmodifiableCollection(knownMappers.keySet());
  }

  /**
   * Adds the mappers.
   *
   * @param packageName
   *          the package name
   * @param superType
   *          the super type
   * @since 3.2.2
   */
  public void addMappers(String packageName, Class<?> superType) {
    ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>();
    resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
    Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
    for (Class<?> mapperClass : mapperSet) {
      addMapper(mapperClass);
    }
  }

  /**
   * Adds the mappers.
   *
   * @param packageName
   *          the package name
   * @since 3.2.2
   */
  public void addMappers(String packageName) {
    addMappers(packageName, Object.class);
  }

}
